package shinesend.com.cn.downloadapk;

import android.os.AsyncTask;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;

/**
 * Created by MyPC on 2016/11/26.
 */
public class DownloadAsync extends AsyncTask<DownLoadEntity,DownLoadEntity,DownLoadEntity> {


    private onProgressUpdate pUpdate;

    public DownloadAsync(onProgressUpdate pUpdate) {
        this.pUpdate = pUpdate;
    }

    @Override
    protected DownLoadEntity doInBackground(DownLoadEntity... params) {
        DownLoadEntity entity = params[0];
        BufferedInputStream inputStream ;
        try {
            RandomAccessFile accessFile = new RandomAccessFile(entity.localPath,"rw");
            URL url = new URL(entity.downLink);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if (connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                //io 流使用的是BuffferedInputStream;
                inputStream = new BufferedInputStream(connection.getInputStream());
                // 总
                int totalSkip = entity.fromBits+entity.progress;
                //当前的;
                int preSkip = 0;
                int tmp = 0;
                while ((tmp=entity.fromBits-entity.progress)!=0){
                    preSkip += tmp;
                }
                byte[] bytes = new byte[1024];
                int bytecount = 0 ;
                //15030456853  903184400
                while((bytecount=inputStream.read(bytes))!=-1){
                    //更新页面
                    publishProgress(entity);
                    if (entity.fromBits+entity.progress+bytecount>entity.toBits){
                        bytecount = entity.toBits - (entity.fromBits+entity.progress);
                        accessFile.write(bytes,0,bytecount);
                    }else{
                        accessFile.write(bytes,0,bytecount);
                    }
                    entity.progress+=bytecount;
                    if (entity.fromBits+entity.progress>=entity.toBits){
                        break;
                    }
                }
            }
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return entity;
    }

    @Override
    protected void onProgressUpdate(DownLoadEntity... values) {
        pUpdate.mainUIUpdate(values[0]);

    }

    public interface onProgressUpdate{
        public void mainUIUpdate(DownLoadEntity entity);
    }

}
